package payuserlogic

import (
	"context"
	"fmt"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/pay"
	"navi-mumbai/common/key/paykey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/uniqueid"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"navi-mumbai/third/pay/epay18"
	"strconv"

	"navi-mumbai/app/rpc/pay/internal/svc"
	"navi-mumbai/app/rpc/pay/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateEpay18DepositLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateEpay18DepositLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateEpay18DepositLogic {
	return &CreateEpay18DepositLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建充值
func (l *CreateEpay18DepositLogic) CreateEpay18Deposit(in *pb.CreateEpay18DepositReq) (*pb.CreateEpay18DepositResp, error) {
	defer utils.RecoverPanic()

	// 校验是否存在正在进行的提现
	var count int64
	var err error
	count, err = l.svcCtx.Epay18DepositFlowModel.CountDepositFlow(l.ctx, in.FlowNo, paykey.Epay18PayStatusDepositWait)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	if count > 0 {
		l.Logger.Errorf("deposit is processing ")
		return nil, xerr.NewGrpcErrCodeMsg(xerr.PaymentFail, "deposit is processing")
	}
	var dAmount decimal.Decimal
	dAmount, err = decimal.NewFromString(in.CurrencyAmount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}

	// 生成充值订单
	df := pay.Epay18DepositFlow{
		FlowNo:       uniqueid.GenFlowNoX(),
		PayChannelId: in.PayChannelId,
		WalletFlowNo: in.FlowNo,
		TradeNo:      "",
		TradeStatus:  "",
		PayUrl:       "",
		Amount:       dAmount.Mul(decimal.NewFromInt(walletkey.MoneyScale)).IntPart(),
		TerminalType: in.DeviceType,
		Channel:      l.svcCtx.Config.PayChannelEPay18Conf.DepositChannel,
		MerchantCode: l.svcCtx.Config.PayChannelEPay18Conf.MerchantCode,
		Uid:          in.Uid,
	}

	// 请求epay18
	var epay18Resp *epay18.DepositApplyResp
	var epay18Req epay18.DepositApplyReq
	epay18Req = epay18.DepositApplyReq{
		Amount:          in.CurrencyAmount,
		Channel:         df.Channel,
		MerchantTradeNo: strconv.FormatInt(df.FlowNo, 10),
		TerminalType:    in.DeviceType,
		UserId:          "1",
	}

	epay18Resp, err = epay18.Hc.DepositApply(l.ctx, &epay18Req)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		l.Logger.Errorf("epay18 deposit apply error%s, req:%+v", err.Error(), epay18Req)
		return nil, xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, err.Error())
	}

	var resp pb.CreateEpay18DepositResp
	//
	if epay18Resp.Status == paykey.Epay18Success {
		df.TradeNo = epay18Resp.TradeNo
		if epay18Resp.TradeStatus != "" {
			df.TradeStatus = epay18Resp.TradeStatus
		} else {
			df.TradeStatus = paykey.Epay18PayStatusDepositWait
		}

		df.PayUrl = epay18Resp.PayUrl
		resp = pb.CreateEpay18DepositResp{
			PayGwFlowNo: df.FlowNo,
			PayUrl:      epay18Resp.PayUrl,
			State:       walletkey.DepositFlowStateWait,
			ExFlowNo:    df.TradeNo,
		}
	} else {
		df.ErrMsg = fmt.Sprintf("%s:%s", epay18Resp.ErrorCode, epay18Resp.Msg)
		resp = pb.CreateEpay18DepositResp{
			PayGwFlowNo: df.FlowNo,
			State:       walletkey.DepositFlowStateFailed,
			ErrMsg:      df.ErrMsg,
		}
	}

	_, err = l.svcCtx.Epay18DepositFlowModel.Insert(l.ctx, &df)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	return &resp, nil
}
